﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using SisCRA.Business;
using SisCRA.Classes;

namespace SisCRA.Forms
{
    public partial class FormDiscipline : Form
    {
        #region -Constructor-

        /// <summary>
        /// Construtor padrão.
        /// </summary>
        public FormDiscipline()
        {
            try
            {
                InitializeComponent();
                LoadDataGridViewDiscipline();
            }
            catch (Exception ex)
            {
                Log.Instance.Error(ex);
                MessageBox.Show(this, "Falha ao buscar dados.\r\nPor favor, verifique suas configurações de conexão com o banco de dados.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region -Events-

        private void dataGridViewDiscipline_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                this.textBoxCode.Text = string.Empty;
                this.textBoxName.Text = string.Empty;
                this.textBoxMaxFaults.Text = string.Empty;

                if (this.dataGridViewDiscipline.SelectedRows.Count == 1)
                {
                    this.textBoxCode.Text = this.dataGridViewDiscipline.SelectedRows[0].Cells[1].Value.ToString();
                    this.textBoxName.Text = this.dataGridViewDiscipline.SelectedRows[0].Cells[2].Value.ToString();
                    this.textBoxMaxFaults.Text = this.dataGridViewDiscipline.SelectedRows[0].Cells[3].Value.ToString();
                }
            }
            catch
            {

            }
        }

        private void buttonSearch_Click(object sender, EventArgs e)
        {
            try
            {
                Discipline discipline = new Discipline();
                discipline.Code = this.textBoxSearchCode.Text;
                discipline.Name = this.textBoxSearchName.Text;

                DisciplineBLL disciplineBLL = new DisciplineBLL();
                this.dataGridViewDiscipline.DataSource = disciplineBLL.GetDisciplineByParam(discipline);
            }
            catch (Exception ex)
            {
                Log.Instance.Error(ex);
                MessageBox.Show(this, "Falha ao buscar a(s) disciplina(s).", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            int totalCount = 0;
            int successCount = 0;

            try
            {
                if (this.openFileDialogImport.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    using (StreamReader sReader = new StreamReader(this.openFileDialogImport.FileName))
                    {
                        string sLine = string.Empty;

                        while (!string.IsNullOrWhiteSpace(sLine = sReader.ReadLine()))
                        {
                            try
                            {
                                totalCount++;

                                string[] arrData = sLine.Split(';', ',');

                                if (arrData.Length == 3)
                                {
                                    if (!string.IsNullOrWhiteSpace(arrData[0]) && arrData[0].Length <= 25 &&
                                        !string.IsNullOrWhiteSpace(arrData[1]) && arrData[1].Length <= 50 &&
                                        !string.IsNullOrWhiteSpace(arrData[2]) && arrData[2].Length <= 2)
                                    {
                                        Discipline discipline = new Discipline();
                                        discipline.Code = arrData[0];
                                        discipline.Name = arrData[1];
                                        discipline.MaxFaults = int.Parse(arrData[2]);

                                        DisciplineBLL disciplineBLL = new DisciplineBLL();
                                        disciplineBLL.SaveDiscipline(discipline);

                                        successCount++;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Instance.Error(ex);
                            }
                        }
                    }

                    CleanFields();
                    LoadDataGridViewDiscipline();

                    if (successCount > 0)
                    {
                        MessageBox.Show(this, "Foram importadas " + successCount + " disciplina(s) de um total de " + totalCount + ".", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(this, "Não foi possível importar nenhuma disciplina. Verifique se o arquivo selecionado está no formato correto.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Instance.Error(ex);
                MessageBox.Show(this, "Falha ao importar disciplina(s).", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void buttonNewDiscipline_Click(object sender, EventArgs e)
        {
            CleanFields();
        }

        private void textBoxMaxFaults_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsNumber(e.KeyChar) || char.IsControl(e.KeyChar)))
            {
                e.Handled = true;
            }
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(textBoxCode.Text) || string.IsNullOrWhiteSpace(textBoxName.Text) || string.IsNullOrWhiteSpace(textBoxMaxFaults.Text))
                {
                    MessageBox.Show(this, "Existem campos inválidos!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    Discipline discipline = new Discipline();
                    if (this.dataGridViewDiscipline.SelectedRows.Count == 1)
                    {
                        discipline.Id = int.Parse(this.dataGridViewDiscipline.SelectedRows[0].Cells[0].Value.ToString());
                    }
                    discipline.Code = this.textBoxCode.Text;
                    discipline.Name = this.textBoxName.Text;
                    discipline.MaxFaults = int.Parse(this.textBoxMaxFaults.Text);

                    DisciplineBLL disciplineBLL = new DisciplineBLL();
                    disciplineBLL.SaveDiscipline(discipline);

                    CleanFields();
                    LoadDataGridViewDiscipline();
                }
            }
            catch (Exception ex)
            {
                Log.Instance.Error(ex);
                MessageBox.Show(this, "Falha ao salvar a disciplina.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        #endregion

        #region -Private Methods-

        /// <summary>
        /// Método que carrega o DataGridViewDiscipline.
        /// </summary>
        private void LoadDataGridViewDiscipline()
        {
            try
            {
                DisciplineBLL disciplineBLL = new DisciplineBLL();
                this.dataGridViewDiscipline.DataSource = disciplineBLL.GetAllDiscipline();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Método que limpa os campos do formulário.
        /// </summary>
        private void CleanFields()
        {
            this.textBoxSearchCode.Text = string.Empty;
            this.textBoxSearchName.Text = string.Empty;
            this.dataGridViewDiscipline.ClearSelection();
            this.textBoxCode.Text = string.Empty;
            this.textBoxName.Text = string.Empty;
            this.textBoxMaxFaults.Text = string.Empty;
            this.textBoxCode.Focus();
        }

        #endregion
    }
}
